package brandroid.BarAndDrink;

import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings.Secure;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.vending.licensing.AESObfuscator;
import com.google.android.vending.licensing.LicenseChecker;
import com.google.android.vending.licensing.LicenseCheckerCallback;
import com.google.android.vending.licensing.Policy;
import com.google.android.vending.licensing.ServerManagedPolicy;


public class mainActivity extends Activity {

	private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi+" +
			"tTzAMR48kaooLKM1e6823IRdcND56RdBg5LLdM0/HElZm7mg0IUeBN1+BIupR1qJtUoCECPDzQ8K83VxAvW9PHCxN9" +
			"sKmPEzUUJVAtHO5ZWQWbcYc/TmroDVYw6y2zlI4lxdOIgSMr4vJcvQJtIfgPjM2tqm495lK4vyrviw+/vWgFdp/HrR8" +
			"Z3mpkw5B4Su1kVfF8S9S3aAucN5GpB3ImHNkVGiQiZwJ3VpaAteor/vVAyjGlLfOLMG6p0EpsrnSw6G20i76/6lKn+esut" +
			"gNYP+N8XABbRgGzA+cRQKajySGS+o4Fj7nXZqd9faUYtxchHh0rFl2EWCWaGXaCdwIDAQAB";
	private static final byte[] SALT = new byte[] {03,26,15,-26,-78,112,58,32,-1,74,12,63,124,41,-23,-89,-72,16,17,21};
	private static String deviceId;// = Secure.getString(getContext().getContentResolver, Secure.ANDROID_ID);
	private EditText searchText;
	private Context context;
	private SQLiteAdapter mySQLiteAdapter;
	private Cursor cursor;
	private ListView listContent;
	public SimpleCursorAdapter cursorAdapter;
	public specials newSpecials;
	public Intent intent;
	private Typeface tf;
	private Parcelable state;
	public boolean searched = false;
	private Button mapButton;
	private Boolean barView;
	private RadioButton showCity;
	private RadioButton allBars;
	private LicenseCheckerCallback mLicenseCheckerCallback;
    private LicenseChecker mChecker;
	
	
	/** Called when the activity is first created. */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		TextView text = (TextView) findViewById(R.id.pageName);
		tf = Typeface.createFromAsset(getAssets(), "fonts/neon2.ttf");
		text.setTypeface(tf);
		// Construct the LicenseCheckerCallback. The library calls this when done.
        mLicenseCheckerCallback = new MyLicenseCheckerCallback();
        deviceId = Secure.getString(getBaseContext().getContentResolver(), Secure.ANDROID_ID);
     // Construct the LicenseChecker with a Policy.
        mChecker = new LicenseChecker(
            this, new ServerManagedPolicy(this,
                new AESObfuscator(SALT, getPackageName(), deviceId)),
            BASE64_PUBLIC_KEY  // Your public licensing key.
            );
        doCheck();
        
		listContent = (ListView) findViewById(R.id.dataListView);
		searchText = (EditText) findViewById(R.id.searchTextBox);
		showCity = (RadioButton)findViewById(R.id.showCityRadioButton);
		allBars = (RadioButton)findViewById(R.id.allBarsRadioButton);
		mySQLiteAdapter = new SQLiteAdapter(this);
		barView = true;
		
		
		fillData();
		
		// Hide keyboard on initial screen open
		context = getApplicationContext();
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

		searchText.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN)
						&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
					
					mySQLiteAdapter.openToRead();
					cursor = mySQLiteAdapter.dataBaseNameQuery(searchText.getText()
							.toString());
					startManagingCursor(cursor);

					String[] from = new String[] { SQLiteAdapter.KEY_NAME,
							SQLiteAdapter.KEY_ID };
					int[] to = new int[] { R.id.rowText };
					updateListView(from, to);
					mySQLiteAdapter.close();
					searchText.setText("");
					searched = true;
					barView = true;
					allBars.setChecked(true);
					
					return true;
				}
				return false;
			}
		});

		mapButton = (Button) findViewById(R.id.mapButton);
		mapButton.setOnClickListener(new Button.OnClickListener() {
		    public void onClick(View v) {
		    	Toast funnyMessage = Toast.makeText(context, "Future add on.", Toast.LENGTH_SHORT);
		    	funnyMessage.show();
//		    	intent = new Intent(mainActivity.this, BarMap.class);
//		    	searched = true;
//				startActivity(intent);
		    }
		});
		
		
		
		listContent.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				final String city = ((TextView)view).getText().toString();
				if (barView)
					getSpecialsData(id);
				else
				{
					//state = listContent.onSaveInstanceState();
					mySQLiteAdapter.openToRead();
					cursor = mySQLiteAdapter.GetBarsByCity(city);
					startManagingCursor(cursor);

					String[] from = new String[] { SQLiteAdapter.KEY_NAME };
					int[] to = new int[] { R.id.rowText };
					updateListView(from, to);
					mySQLiteAdapter.close();
					barView = true;
				}
					

			}
		});
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		if (showCity.isChecked()){
			mySQLiteAdapter.openToRead();
			cursor = mySQLiteAdapter.GetCities();
			startManagingCursor(cursor);

			String[] from = new String[] { SQLiteAdapter.KEY_CITY };
			int[] to = new int[] { R.id.rowText };
			updateListView(from, to);
			mySQLiteAdapter.close();
			barView = false;
		}
		else
			fillData();
//		if (searched){
//			fillData();
//		}
//		else {
//			if(allBars.isChecked()){
//				listContent.setAdapter(cursorAdapter);
//				listContent.onRestoreInstanceState(state);
//			}
//			else{
//				mySQLiteAdapter.openToRead();
//				cursor = mySQLiteAdapter.GetCities();
//				startManagingCursor(cursor);
//
//				String[] from = new String[] { SQLiteAdapter.KEY_CITY };
//				int[] to = new int[] { R.id.rowText };
//				updateListView(from, to);
//				mySQLiteAdapter.close();
//			}
//		}
	}
	
	public void ShowCity_Click(View v){
		
		barView = false;
		mySQLiteAdapter.openToRead();
		cursor = mySQLiteAdapter.GetCities();
		startManagingCursor(cursor);

		String[] from = new String[] { SQLiteAdapter.KEY_CITY };
		int[] to = new int[] { R.id.rowText };
		updateListView(from, to);
		mySQLiteAdapter.close();
		//state = listContent.onSaveInstanceState();
	}
	
	public void AllBars_Click(View v){
		
		barView = true;
		mySQLiteAdapter.openToRead();
		cursor = mySQLiteAdapter.queueAll();
		startManagingCursor(cursor);

		String[] from = new String[] { SQLiteAdapter.KEY_NAME };
		int[] to = new int[] { R.id.rowText };
		updateListView(from, to);
		mySQLiteAdapter.close();
		//state = listContent.onSaveInstanceState();
	}
	
	
	public void updateListView(String[] from, int[] to) {
		cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor,
				from, to);

		listContent.setAdapter(cursorAdapter);
	}

	public void getSpecialsData(long id) {
		state = listContent.onSaveInstanceState();
		Bundle data = new Bundle();
		mySQLiteAdapter.openToRead();
		cursor = mySQLiteAdapter.dataBaseSpecialsQuery(String.valueOf(id));
		startManagingCursor(cursor);
		cursor.moveToFirst();
		intent = new Intent(mainActivity.this, specials.class);
		
		data.putString("Sunday", cursor.getString(1));
		data.putString("Monday", cursor.getString(2));
		data.putString("Tuesday", cursor.getString(3));
		data.putString("Wednesday", cursor.getString(4));
		data.putString("Thursday", cursor.getString(5));
		data.putString("Friday", cursor.getString(6));
		data.putString("Saturday", cursor.getString(7));
		
		cursor = mySQLiteAdapter.dataBaseQuery(String.valueOf(id));
		startManagingCursor(cursor);
		cursor.moveToFirst();
		
		data.putString("barName", cursor.getString(1));
		data.putString("barAddress", cursor.getString(2));
		data.putString("barCity", cursor.getString(3));
		data.putString("barState", cursor.getString(4));
		data.putString("barZip", cursor.getString(5));
		data.putString("barWebAddress", cursor.getString(7));
		
		intent.putExtras(data);
		startActivity(intent);

		cursor.close();	
	}
	
	

	private void fillData() {

		searched = false;
		mySQLiteAdapter.openToRead();
		try {
			mySQLiteAdapter.copyDataBase();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		cursor = mySQLiteAdapter.queueAll();
		//cursor = mySQLiteAdapter.GetCities();
		startManagingCursor(cursor);

		//String[] from = new String[] { SQLiteAdapter.KEY_CITY };
		String[] from = new String[] { SQLiteAdapter.KEY_NAME };
		int[] to = new int[] { R.id.rowText };
		cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor,
				from, to);
		listContent.setAdapter(cursorAdapter);
		barView = true;

	}
	
	

	@Override
    public void onSaveInstanceState(Bundle savedInstanceState){
        super.onSaveInstanceState(savedInstanceState);
               //savedInstanceState.putString("message", text.getText().toString());
    }
 
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);
        //message = savedInstanceState.getString("message");
    }
    
    private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
        public void allow(int reason) {
            if (isFinishing()) {
                // Don't update UI if Activity is finishing.
                return;
            }
            // Should allow user access.
            //displayResult(getString(R.string.allow));
        }

        public void dontAllow(int reason) {
            if (isFinishing()) {
                // Don't update UI if Activity is finishing.
                return;
            }
            //displayResult(getString(R.string.dont_allow));
            
            if (reason == Policy.RETRY) {
                // If the reason received from the policy is RETRY, it was probably
                // due to a loss of connection with the service, so we should give the
                // user a chance to retry. So show a dialog to retry.
               // showDialog(DIALOG_RETRY);
            } else {
                // Otherwise, the user is not licensed to use this app.
                // Your response should always inform the user that the application
                // is not licensed, but your behavior at that point can vary. You might
                // provide the user a limited access version of your app or you can
                // take them to Google Play to purchase the app.
                //showDialog(DIALOG_GOTOMARKET);
            }
        }

		@Override
		public void applicationError(int errorCode) {
			// TODO Auto-generated method stub
			
		}
    }
    
    private void doCheck() {
        //mCheckLicenseButton.setEnabled(false);
        setProgressBarIndeterminateVisibility(true);
        //mStatusText.setText(R.string.checking_license);
        mChecker.checkAccess(mLicenseCheckerCallback);
    }

}